package com.yiyihealth.cherriesadmin.core.quartz;

import com.yiyihealth.cherriesadmin.model.jkt.JThealth;
import com.yiyihealth.cherriesadmin.model.jkt.JktFunc10009;
import com.yiyihealth.cherriesadmin.service.OrdAppointmentService;
import org.springframework.data.redis.core.StringRedisTemplate;
import cn.hutool.extra.spring.SpringUtil;
import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.springframework.beans.factory.annotation.Autowired;



import java.util.Optional;

/**
 * @author 10560
 */
public class SchedulerQuartzJob implements Job {

    @Autowired
    private StringRedisTemplate stringRedisTemplate ;
    @Autowired
    private JktFunc10009 jktFunc10009;
    @Autowired
    private JThealth jThealth;
    @Autowired
    private OrdAppointmentService appointmentService;


    private void before(){
        System.out.println("任务开始执行！");
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        before();
        System.out.println("开始：" + System.currentTimeMillis());
        // TODO 业务
        //获得传递过来的参数
        JobDataMap jdMap = jobExecutionContext.getJobDetail().getJobDataMap();

        if (!Optional.ofNullable(stringRedisTemplate).isPresent()){
            stringRedisTemplate = (StringRedisTemplate) SpringUtil.getBean("stringRedisTemplate");
        }
        String schedulingIdKey   = jdMap.get("schedulingIdKey").toString();
        String sourceDetailIdKey = jdMap.get("sourceDetailIdKey").toString();
        String sourceDetailId    = jdMap.get("sourceDetailId").toString();
        String appointmentId    = jdMap.get("appointmentId").toString();
        System.out.println("key: "+sourceDetailId);
        stringRedisTemplate.opsForValue().increment(schedulingIdKey,1);
        stringRedisTemplate.opsForSet().add(sourceDetailIdKey,sourceDetailId);

        System.out.println("结束：" + System.currentTimeMillis());
        try {
            after(sourceDetailId,appointmentId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void after(String sourceDetailId,String appointmentId) throws Exception {
        try {
            Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
            TriggerKey triggerKey = new TriggerKey(sourceDetailId, "group2");
            JobKey jobKey = new JobKey(sourceDetailId, "group2");
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 删除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
            System.out.println("释放号源成功！");
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        System.out.println("任务结束执行！");
    }
}
